package com.zzyl.intercept;

import cn.hutool.json.JSONUtil;
import com.zzyl.constant.SuperConstant;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.properties.JwtTokenManagerProperties;
import com.zzyl.properties.SecurityConfigProperties;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.UserThreadLocal;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Component
public class AdminInterceptor implements HandlerInterceptor{
    @Autowired
    private JwtTokenManagerProperties jwtTokenManagerProperties;
    @Autowired
    private SecurityConfigProperties securityConfigProperties;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("authorization");
        if (token == null || token == ""){
            throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
        }
        else {
            try {
                //有token，解析token
                Claims claims = JwtUtil.parseJWT(jwtTokenManagerProperties.getBase64EncodedSecretKey(), token);
                if (claims == null || claims.isEmpty()){
                    throw new BaseException(BasicEnum.LOGIN_LOSE_EFFICACY);
                }
                Long userId = (Long) claims.get("id");
                //读取白名单和redis中的资源名单
                //获取请求中的uri
                String requestURI = request.getRequestURI();
                //获取请求方式
                String method = request.getMethod();
                String requestPath = method + requestURI;
                String json = redisTemplate.opsForValue().get(SuperConstant.PUBLIC_ACCESS_URLS + userId);
                List<String> publicAccessUrls = securityConfigProperties.getPublicAccessUrls();
                List<String> requestPaths = JSONUtil.toList(json, String.class);
                requestPaths.addAll(publicAccessUrls);
                for (String path : requestPaths) {
                    if (antPathMatcher.match(path,requestPath)){
                        UserThreadLocal.set(userId);
                        return true;
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
                throw new BaseException(BasicEnum.LOGIN_FAIL);
            }

        }
        throw new BaseException(BasicEnum.SECURITY_ACCESSDENIED_FAIL);
    }


}
